#include "ConfigService.h"

StaticJsonBuffer<512> configBuffer;

void ConfigService::loadConfig()
{
    // Open file for reading
    if (!SD.exists(CONFIG_PATH)) {
        initConfig();
        return;
    }

    File file = SD.open(CONFIG_PATH);

    JsonObject & configuration = configBuffer.parseObject(file);
    for (auto item : configuration) {
        config[item.key] = item.value.as<char*>();
    }

    if (!configuration.success()) {
        initConfig();
    }
}

void ConfigService::saveConfig()
{
    Serial.println("saving config file...");
    // Delete existing file, otherwise the configuration is appended to the file
    if (SD.exists(CONFIG_PATH)) {
        SD.remove(CONFIG_PATH);
    }

    // Open file for writing
    File file = SD.open(CONFIG_PATH, FILE_WRITE);
    if (!file) {
        Serial.println(F("Failed to create file"));
        return;
    }

    JsonObject & configuration = configBuffer.createObject();
    for (auto item : config) {
        configuration[String(item.first.c_str())] = String(item.second.c_str());
    }

    // Serialize JSON to file
    if (configuration.printTo(file) == 0) {
        Serial.println(F("Failed to write to file"));
    }

    Serial.print(F("config file saved: "));
    configuration.prettyPrintTo(Serial);
    Serial.println();
    // Close the file (File's destructor doesn't close the file)
    file.close();
}

string ConfigService::getConfig(const char * key)
{
    if (config.count(key) != 0)
    {
        return config[key];
    }
    return "";
}

void ConfigService::setConfig(const char * key, const char * value)
{
    config[key] = value;
}

void ConfigService::initConfig()
{
    Serial.print("init config file: ");
    config.clear();
    JsonObject & configuration = configBuffer.parseObject(INIT_CONFIG);
    for (auto item : configuration) {
        config[item.key] = item.value.as<char*>();
    }
    configuration.prettyPrintTo(Serial);
    Serial.println();
    saveConfig();
}

ConfigService configService;